package com.woniuxy.cq.phrase3.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.cq.phrase3.common.EncryptUtil;
import com.woniuxy.cq.phrase3.common.Result;
import com.woniuxy.cq.phrase3.controller.component.MyException;
import com.woniuxy.cq.phrase3.controller.form.ChangeUserRoleForm;
import com.woniuxy.cq.phrase3.controller.form.ProjectForm;
import com.woniuxy.cq.phrase3.controller.form.UserForm;
import com.woniuxy.cq.phrase3.controller.form.UserFormLogin;
import com.woniuxy.cq.phrase3.dao.UserMapper;
import com.woniuxy.cq.phrase3.entity.Country;
import com.woniuxy.cq.phrase3.entity.Industry;
import com.woniuxy.cq.phrase3.entity.Role;
import com.woniuxy.cq.phrase3.entity.User;
import com.woniuxy.cq.phrase3.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 用户业务层
 * @author Lucas
 * @since 2020-09-07
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserMapper userMapper;
    /**
     * 注册业务
     * @param userForm
     */
    @Override
    @Transactional
    public void register(UserForm userForm) {
        //1.判断是否存在该用户名
        User user = userMapper.findByName(userForm.getUserName());
        if(user != null){ throw new MyException("该用户名已存在"); }
        //2.可以注册 新增到user表 获取4位的随机盐
        userForm.setUserSalt(EncryptUtil.getSalt(4));
        userForm.setUserPass(EncryptUtil.encrypt(userForm.getUserPass(),userForm.getUserSalt()));
        userMapper.addUser(userForm);
        User byName = userMapper.findByName(userForm.getUserName());
        //3.给注册的普通用户 提供普通级权限
        userMapper.addJurisdiction(byName.getUserId(),1);
    }

    /**
     * 登陆业务
     * @param userFormLogin
     */
    @Override
    public Result login(UserFormLogin userFormLogin) {
        //1.获取subject
        Subject currUser = SecurityUtils.getSubject();
        //2.获得token
        AuthenticationToken token = new UsernamePasswordToken(userFormLogin.getUserName(), userFormLogin.getUserPass());
        //3.调用登陆
        try {
            currUser.login(token);

            User user = userMapper.findByName(userFormLogin.getUserName());
            //登陆成功 返回该用户的id
            boolean isManager = currUser.hasRole("applicant");
            boolean isCommit = currUser.isPermitted("submit");
            System.out.println("isManager:"+isManager+"isCommit:"+isCommit);
            return Result.success(user);
        }catch (AuthenticationException e){
            e.printStackTrace();
            return Result.fail("500","登陆失败");
        }
    }

    /**
     * 检验用户名是否存在
     * @param username
     * @return
     */
    @Override
    public Result checkByUserName(String username) {
        User user = userMapper.findByName(username);
        if(user == null){
            return Result.fail("500","用户不存在");
        }else {
            return Result.success("用户存在");
        }
    }

    @Override
    public String findRolesByUserId(Integer id) {
        String rolesById = userMapper.findRolesByUserId(id);
        return rolesById;
    }

    /**
     * 项目申请
     * @param projectForm
     */
    @Override
    public void applicationProject(ProjectForm projectForm) {
        //1.补充数据
        Date date = new Date();
        projectForm.setProjectTime(date);
        projectForm.setProjectUpdateTime(date);
        projectForm.setProjectResult("未受理");
        //2.新增到数据库
        userMapper.addProject(projectForm);
    }

    @Override
    public List<Industry> getAllIndustry() {
        return userMapper.getAllIndustry();
    }

    @Override
    public List<Country> getAllCountry() {
        return userMapper.getAllCountry();
    }

    /**
     * 删除User
     * @param userId
     */
    @Override
    public void deleteUserById(Integer userId) {
        userMapper.deleteUserById(userId);
        userMapper.deleteUserRoleByUserId(userId);
    }

    /**
     * 更新用户信息
     * @param userForm
     */
    @Override
    public int updateUserByUserForm(UserForm userForm) {
        if(userForm.getUserName() == null){
            userMapper.updateUserByUserForm(userForm);
        }else {
            User byName = userMapper.findByName(userForm.getUserName());
            if(byName != null){ //用户名已存在 不能修改
                return 1;
            }else if(userForm.getUserPhone().length() != 11){
                return 2;
            }
            userMapper.updateUserByUserForm(userForm);
            return 0;
        }
        return 0;
    }

    /**
     * 分页查询User 带条件
     * @param userForm
     * @return
     */
    @Override
    public PageInfo<UserForm> queryAllByPage(UserForm userForm) {
        System.out.println("当前页:"+userForm.getPageNum()+"每页显示数量:"+userForm.getPageSize());
        PageHelper.startPage(userForm.getPageNum(),userForm.getPageSize());
        List<UserForm> all = userMapper.queryAllByPage(userForm);
        PageInfo<UserForm> LecturerFormPageInfo = new PageInfo<>(all);
        return LecturerFormPageInfo;
    }

    @Override
    public List<Role> getAllRole() {
        return userMapper.getAllRole();
    }

    @Override
    public void changeRole(ChangeUserRoleForm changeUserRoleForm) {
        //userMapper.updateuserOfficeIdBychangeUserRoleForm(changeUserRoleForm);
        userMapper.updateuserOfficeIdBychangeUserRoleForm(changeUserRoleForm.getUserId(),changeUserRoleForm.getUserOfficeId());

        userMapper.changeRole(changeUserRoleForm);

    }
}
